<template>
  <div id="uploadImage">
    <el-upload
      v-show="!isShowProgress"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :class="{ display: fileList.length }"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="onRequest"
      :on-preview="handlePictureCardPreview"
      :before-upload="beforeUpload"
      accept="image/png, image/jpeg"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

var cos = new COS({
  SecretId: 'AKIDvnZDlCTbbTCnEZlplaHqJdnoiU7c0GOO',
  SecretKey: 'ueAe8WxGOIxZ6WllYEhwvhFblgMm01pQ'
})

export default {
  name: 'UploadImage',
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      currentUid: '',
      percentage: 100, // 进度条
      isShowProgress: false
    }
  },

  // 定义方法
  methods: {
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    onRequest(data) {
      cos.putObject({
        Bucket: 'li-hr-1307760705', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: data.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        if (!err && data.statusCode === 200) {
          const url = 'http://' + data.Location
          const index = this.fileList.findIndex(item => item.uid === this.currentUid)
          this.fileList[index].url = url
          this.$emit('on-success', url, this.fileList)
          setTimeout(() => {
            this.isShowProgress = false
          }, 500)
        } else {
          this.$message.error('上传失败！')
          this.isShowProgress = false
          this.fileList = this.fileList.filter(item => item.uid !== this.currentUid)
        }
      })
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    beforeUpload(file) {
      const maxSize = 1 * 1024 * 1024 // 1MB
      if (maxSize < file.size) {
        this.$message('限制1MB大小的图片')
        return false
      }
      this.currentUid = file.uid
      this.isShowProgress = true
      return true
    }
  }
}
</script>

<style scoped lang="scss">
#uploadImage {
  ::v-deep .display .el-upload--picture-card {
    display: none;
  }
  ::v-deep .el-dialog__headerbtn {
    top: 8px;
    right: 8px;
  }
}
</style>
